/*
 * Copyright 2021 Wicrenet, Inc. All rights reserved.
 */
package com.yinshu.teleshield.tkbase.controller.helper;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 【easyExecl 设置多个下拉选项】
 *
 * @author yangjunxiong
 * Created on 2021/12/28 09:33
 */
public class PlusSheetWriteHandler implements SheetWriteHandler {

    private Map<Integer, String[]> map;

    public Integer lastRow;

    private int index;

    public PlusSheetWriteHandler(Map<Integer, String[]> map, Integer lastRow) {
        this.map = map;
        this.lastRow = lastRow;
        this.index = 0;
    }

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        if (map.isEmpty()) {
            return;
        }
        DataValidationHelper helper = writeSheetHolder.getSheet().getDataValidationHelper();
        Workbook workbook = writeWorkbookHolder.getWorkbook();
        List<Integer> setSheetHidden = new ArrayList<>();
        map.forEach((k, v) -> {
            String sheetName = "sheet" + k;
            Sheet proviceSheet = workbook.createSheet(sheetName);
            this.index++;
            setSheetHidden.add(this.index);
            for (int i = 0, length = v.length; i < length; i++) {
                proviceSheet.createRow(i).createCell(0).setCellValue(v[i]);
            }
            Name category1Name = workbook.createName();
            category1Name.setNameName(sheetName);
            category1Name.setRefersToFormula(sheetName + "!$A$1:$A$" + (v.length));
            CellRangeAddressList addressList = new CellRangeAddressList(1, lastRow, k, k);
            DataValidationConstraint constraint8 = helper.createFormulaListConstraint(sheetName);
            DataValidation dataValidation3 = helper.createValidation(constraint8, addressList);
            dataValidation3.setSuppressDropDownArrow(true);
            dataValidation3.createErrorBox("提示", "请输入下拉框存在的选项");
            dataValidation3.setShowErrorBox(true);
            writeSheetHolder.getSheet().addValidationData(dataValidation3);
        });
        setSheetHidden.forEach(index -> workbook.setSheetHidden(index, true));
    }

}
